﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;

namespace blackhouse.Web.PageRequests {
	public class PageRequestParameters {

		#region Fields

		private Page page;

		#endregion

		#region Methods

		#region Public

		public string GetUrl(PageRequestParameter parameter) {
			return this.GetUrl(parameter, "");
		}

		public string GetUrl(PageRequestParameter parameter, string storeName) {
			var parameters = from st in this.getStore() select st.Value;

			if(!string.IsNullOrEmpty(storeName))
				parameters = from st in this.getStore(storeName) select st.Value;

			parameters = from pr in parameters where pr.CategoryId != parameter.CategoryId orderby pr.Order, pr.CategoryId select pr;
			List<PageRequestParameter> lParameters = parameters.ToList();
			lParameters.Add(parameter);

			return this.buildUrl(lParameters);
		}

		public void Register(PageRequestParameter parameter) {
			this.Register(parameter, "pagerequests");
		}

		public void Register(PageRequestParameter parameter, string storeName) {
			Dictionary<string, PageRequestParameter> store = this.getStore(storeName);
			if(store.ContainsKey(parameter.CategoryId))
				store[parameter.CategoryId] = parameter;
			else
				store.Add(parameter.CategoryId, parameter);
		}

		#endregion

		#region Private

		protected virtual string buildUrl(IEnumerable<PageRequestParameter> parameters) {
			Dictionary<string, string> newParameters = new Dictionary<string, string>();
			foreach(PageRequestParameter parameter in parameters) {
				newParameters.Add(parameter.CategoryId, parameter.Value.ToString());
			}
			return WebUtils.GetNewAddress(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path), newParameters, new List<string>());
		}

		private Dictionary<string, PageRequestParameter> getStore() {
			return this.getStore("pagerequests");
		}

		private Dictionary<string, PageRequestParameter> getStore(string storeName) {
			if(this.page == null)
				this.page = HttpContext.Current.Handler as Page;
			if(!this.page.Items.Contains(storeName))
				this.page.Items.Add(storeName, new Dictionary<string, PageRequestParameter>());

			return this.page.Items[storeName] as Dictionary<string, PageRequestParameter>;
		}

		#endregion

		#endregion

	}
}